package com.metagurukul.metaboard.action;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import com.metagurukul.metaboard.dao.*;
import com.metagurukul.metaboard.model.notification.*;

public class SearchAction extends Action {
	private final static String SUCCESS = "success";
	private final static String FAILURE = "failure";

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Notification notification = (Notification) form;
		NotificationDAO notificationDao = new NotificationDAO();
		ArrayList<Notification> notices = new ArrayList<Notification>();
		String searchType = request.getParameter("search").trim();

		if (searchType.equals("")) {
			return mapping.findForward(FAILURE);
		} else {
			if (searchType.equals("searchByDate")) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");

				Date date = (Date) dateFormat.parse(searchType);

				notices = notificationDao.searchByDate(date);
				if (notices == null)
					return mapping.findForward(FAILURE);
				else {
					request.setAttribute("result", notices);
					return mapping.findForward(SUCCESS);
				}
			}
			if (searchType.equals("searchByCreater")) {
				notices = notificationDao.searchByCreator(searchType);
				if (notices == null)
					return mapping.findForward(FAILURE);
				else {
					request.setAttribute("result", notices);
					return mapping.findForward(SUCCESS);
				}
			}

			if (searchType.equals("searchByTitle")) {
				notices = notificationDao.searchByTitle(searchType);
				if (notices == null)
					return mapping.findForward(FAILURE);
				else {
					request.setAttribute("result", notices);
					return mapping.findForward(SUCCESS);
				}
			}
			return mapping.findForward(FAILURE);
		}
	}
}
